//
//  XGMineViewController.m
//  BSBuDeJie
//
//  Created by monkey on 2018/12/10.
//  Copyright © 2018 itcast. All rights reserved.
//

#import <SVProgressHUD/SVProgressHUD.h>

#import "XGMineTableViewController.h"
#import "XGWebViewController.h"
#import "XGNavigationController.h"
#import "XGSettingTableViewController.h"

#import "XGSquareCollectionViewCell.h"

#import "XGDataManager.h"

#import "XGSquareModel.h"

/// 重用标识符
static NSString *const reuseIdentifier = @"XGSquareCollectionViewCell";

/// 列数
static NSInteger kColumns;
/// 间距
static const CGFloat KMargin = 2;
/// 每一个格子大小
static CGFloat KItemWidth;

@interface XGMineTableViewController () <UICollectionViewDataSource,UICollectionViewDelegate,XGWebViewControllerDelegate>

/// 辅助功能数据模型
@property (nonatomic,strong) NSArray<XGSquareModel *> *dataArray;
/// tableView的footerView
@property (nonatomic,strong) UICollectionView *squareCollectionView;

@end

@implementation XGMineTableViewController

#pragma mark - 控制器生命周期方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 设置导航栏内容
    [self setUpNavigationItem];
    // 设置tableView
    [self setUpTableView];
    // 加载数据
    [self loadData];
}

#pragma mark - 事件监听

- (void)settingAction
{
    XGSettingTableViewController *setting =  [XGSettingTableViewController tableViewControllerWithPlistName:@"setting"];
    [self.navigationController pushViewController:setting animated:YES];
}

#pragma mark - 其他系统方法

+ (void)initialize
{
    kColumns = (Iphone6 ? 4 : 5);
    KItemWidth = (SCREEN_WIDTH - (kColumns - 1) * KMargin) / kColumns;
}

#pragma mark - 内部私有方法

// 设置导航栏
- (void)setUpNavigationItem
{
    UIBarButtonItem *rightItem1 =  [[UIBarButtonItem alloc] initWithCustomView:[UIButton buttonWithImageName:@"mine-setting-icon" highlightedImageName:@"mine-setting-icon-click" target:self action:@selector(settingAction)]];
    UIBarButtonItem *rightItem2 = [[UIBarButtonItem alloc] initWithCustomView:[UIButton buttonWithImageName:@"mine-moon-icon" highlightedImageName:@"mine-moon-icon-click" target:nil action:nil]];
   
    self.navigationItem.rightBarButtonItems = @[rightItem1,rightItem2];
}

// 设置TableView
- (void)setUpTableView
{
    // 设置tableView内容边距
    self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);
    // 设置组头组尾高度
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.sectionFooterHeight = 10;
    
    // 设置FooterView
    [self setUpTableFooterView];
}

// 设置TableFooterView
- (void)setUpTableFooterView
{
    // 设置squareCollectionView
    self.squareCollectionView.dataSource = self;
    self.squareCollectionView.delegate = self;
    self.squareCollectionView.scrollEnabled = NO;
    self.tableView.tableFooterView = self.squareCollectionView;

    // 注册squareCollectionViewCell
    [self.squareCollectionView registerClass:[XGSquareCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

    
    // 设置squareCollectionView布局
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.squareCollectionView.collectionViewLayout;
 
    flowLayout.itemSize = CGSizeMake(KItemWidth, KItemWidth);
    flowLayout.minimumLineSpacing = KMargin;
    flowLayout.minimumInteritemSpacing = KMargin;
}

// 加载数据
- (void)loadData
{
    [SVProgressHUD showWithStatus:@"正在加载中"];
    [XGDataManager loadSquareList:^(NSArray<XGSquareModel *> * _Nullable dataArray, NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        if (error) {
            DEBUG_Log(@"加载辅助功能数据失败!");
            return;
        }
        
        // 处理模型数量
        [self resolveSquareModel:dataArray];
        [self.squareCollectionView reloadData];
        // 计算有多少行 固定格式 (count - 1) / 列数 + 1
        NSInteger rows = (dataArray.count - 1) / kColumns + 1;
        // 计算squareCollectionView的高度
        CGFloat height = rows * KItemWidth + (rows - 1) * KMargin;
        self.squareCollectionView.height = height;
        // 重新给tableView赋值 让tableView自动计算contentSize
        self.tableView.tableFooterView = self.squareCollectionView;
    }];
}

- (void)resolveSquareModel:(NSArray<XGSquareModel *> *)dataArray
{
    // 如果模型不能填充满 追加空模型
    if (dataArray.count % kColumns == 0) {
        self.dataArray = dataArray;
        return;
    } else {
        CGFloat extraCount = kColumns - (dataArray.count % kColumns);
        NSMutableArray<XGSquareModel *> *tempArrayM = [NSMutableArray arrayWithArray:dataArray];
        for (int i = 0; i < extraCount; i++) {
            [tempArrayM addObject:[[XGSquareModel alloc] init]];
        }
        
        self.dataArray = [tempArrayM copy];
    }
}

#pragma mark - UICollectionViewDataSource,UICollectionViewDelegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XGSquareCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.squareModel = self.dataArray[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    XGSquareModel *squareModel = self.dataArray[indexPath.item];
    if (![squareModel.url containsString:@"http"]) {
        return;
    } else {
        XGWebViewController *webViewController = [XGWebViewController webViewControllerWithURL:[NSURL URLWithString:squareModel.url]];
        webViewController.delegate = self;
        XGNavigationController *nav = [[XGNavigationController alloc] initWithRootViewController:webViewController];
        [self presentViewController:nav animated:YES completion:nil];
    }
}

#pragma mark - XGWebViewControllerDelegate

- (void)webViewControllerGoBackAction:(XGWebViewController *)webViewController
{
    [webViewController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 懒加载

- (UICollectionView *)squareCollectionView
{
    if (_squareCollectionView == nil) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _squareCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _squareCollectionView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    }
    
    return _squareCollectionView;
}

@end
